﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DevTools.HardDiskVisualizer.Components
{
    public class Folder : IEnumerable<Folder>
    {
        private static int _idSeed;

        public static int DeepestDepth { get; set; }

        public Folder(string path)
        {
            ID = ++_idSeed;
            Path = path;
            Name = System.IO.Path.GetFileName(Path);

            Children = new List<Folder>();
        }

        public Folder(string path, int depth, int parentID) : this(path)
        {
            ParentID = parentID;
            Depth = depth;

            if (Depth > DeepestDepth)
                DeepestDepth = Depth;
        }

        public int ID { get; private set; }

        public int ParentID { get; private set; }

        public string Path { get; private set; }

        public long Size { get; set; }

        public long SizeInKB
        {
            get { return Size / 1024; }
        }

        public long SizeInMB
        {
            get { return Size / (1024 * 1024); }
        }

        public int Depth { get; private set; }

        public List<Folder> Children { get; private set; }

        public string Name { get; private set; }

        public void AddChildren(IEnumerable<DirectoryInfo> directoryInfoes)
        {
            Children.AddRange(directoryInfoes.Select(x => new Folder(x.FullName, Depth + 1, ID)));
        }

        public void CalculateSum()
        {
            Size += Children.Sum(x => x.Size);
        }

        public IEnumerator<Folder> GetEnumerator()
        {
            foreach (var child in Children)
                yield return child;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
